package com.siysoft.util;


import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.reflect.Reflection;


/**
 * @author SunChaoqun
 * 
 */

public class COMMON {

    public static final double SingleClassDiscount = 0.9;//班科

	public static final double BankeClassDiscount = 0.9;//班课固定折扣

	public static String phone400 = "4006968787";
    
	/**
	 * 
	 * 开发者需要填写 apiKey 和 appId , apiKey 可以在 ping++ 管理平台【应用信息里面查看】
	 * 
	 * apiKey 有 TestKey 和 LiveKey 两种。 
	 * 
	 * TestKey 模式下不会产生真实的交易。
	 */
    
	/**
	 * pingpp 管理平台对应的 API key
	 */
	public static String apiTestKey = "sk_test_HiT4uD4G4OKOSS0OiPPiHunP";
	public static String apiLiveKey = "sk_live_wNawDRVrG88Xcj7fypp22VNR";
	
	/**
	 * pingpp 管理平台对应的应用 ID
	 */
	public static String appId = "app_5qHCOS8yvHmT0Wr5";
	
	public static String home_url = "http://123.57.164.31:8080/tc_platform/";

	//public static String building_url = "http://www.yihaoxue.net/building.html";



    /**
     * 判断某个对象是否为空 集合类、数组做特殊处理
     * 
     * @param obj
     * @return 如为空，返回true,否则false
     * @author yehailong
     */
    public static boolean isEmpty(Object obj) {
        if (obj == null)
            return true;

        // 如果不为null，需要处理几种特殊对象类型
        if (obj instanceof String) {
            return ((String) obj).trim().equals("");
        } else if (obj instanceof Collection) {
            // 对象为集合
            Collection coll = (Collection) obj;
            return coll.size() == 0;
        } else if (obj instanceof Map) {
            // 对象为Map
            Map map = (Map) obj;
            return map.size() == 0;
        } else if (obj.getClass().isArray()) {
            // 对象为数组
            return Array.getLength(obj) == 0;
        } else {
            // 其他类型，只要不为null，即不为empty
            return false;
        }
    }

    /**
     * 字符串是否为数字
     * 
     * @param str
     * @return
     */
    public static boolean isDigitalString(String str) {
        if (isEmpty(str)) {
            return false;
        } else {
            try {
                Double.parseDouble(str);
                return true;
            } catch (Exception e) {
                return false;
            }
        }
    }






    /**
     * 取时间差
     * 
     * @param timestamp1
     * @param timestamp2
     * @param showSecond 是否显示秒
     * @return
     */
    public static String getTimeInterval(Timestamp timestamp1, Timestamp timestamp2, boolean showSecond) {
        if (timestamp1 == null || timestamp2 == null)
            return "";
        StringBuffer buf = new StringBuffer();
        long time1 = timestamp1.getTime();
        long time2 = timestamp2.getTime();
        long time = Math.abs(time1 - time2);
        // day
        long day = time / (24 * 60 * 60 * 1000L);
        // hour
        time = time - day * 24 * 60 * 60 * 1000L;
        long hour = time / (60 * 60 * 1000L);
        // minute
        time = time - hour * 60 * 60 * 1000L;
        long minute = time / (60 * 1000L);
        // second
        time = time - minute * 60 * 1000L;
        long second = time / 1000L;

        if (day != 0) {
            buf.append(day + "天");
        }
        if (hour != 0) {
            buf.append(hour + "时");
        }
        if (minute != 0) {
            buf.append(minute + "分");
        }

        if (showSecond || buf.length() == 0) {
            if (second != 0) {
                buf.append(second + "秒");
            }
        }

        return buf.toString();
    }

    /**
     * 转换字符串至HTML格式
     * 
     * @param src
     * @return
     */
    public static String toHtmlStr(String src) {
        if (src == null || src.length() == 0)
            return "";
        int i;
        StringBuffer aimStrBuf = new StringBuffer();
        StringBuffer resStrBuf = new StringBuffer(src);
        int strLength = resStrBuf.length();
        char tmpChar = 0;
        for (i = 0; i < strLength; i++) {
            tmpChar = resStrBuf.charAt(i);
            if (tmpChar == '<') {
                aimStrBuf.append(new char[] { '&', 'l', 't', ';' });
            } else if (tmpChar == '<') {
                aimStrBuf.append(new char[] { '&', 'g', 't', ';' });
            } else if (tmpChar == '\n') {
                aimStrBuf.append(new char[] { '<', 'b', 'r', '>' });
            } else if (tmpChar == '\r') {} else if (tmpChar == '\t') {
                aimStrBuf.append(new char[] { '&', 'n', 'b', 's', 'p', ';', '&', 'n', 'b', 's', 'p', ';', '&', 'n',
                        'b', 's', 'p', ';', '&', 'n', 'b', 's', 'p', ';' });
            } else if (tmpChar == ' ') {
                aimStrBuf.append(new char[] { '&', 'n', 'b', 's', 'p', ';' });
            } else if (tmpChar == '"') {
                aimStrBuf.append(new char[] { '\\', '“' });
            } else if (tmpChar == '\'') {
                aimStrBuf.append(new char[] { '\\', '\'' });
            } else if (tmpChar == '\\') {
                aimStrBuf.append(new char[] { '\\', '\\' });
            } else {
                aimStrBuf.append(tmpChar);
            }
        }
        return aimStrBuf.toString();
    }

  
    public static void debug(String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.debug(message);
    }

    /**
     * @param message
     */
    public static void info(String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.info(message);
    }
    
    /**
     * @param message
     */
    public static void info(String flag,String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.info("[" + flag + "] " +message);
    }
    
    /**
     * @param message
     */
    public static void info(String flag1,String flag2,String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.info("[" + flag1 + "] " + "[" + flag2 + "] " +message);
    }

    /**
     * @param message
     */
    public static void warn(String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.warn(message);
    }

    /**
     * @param message
     */
    public static void error(String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.error(message);
    }

    /**
     * @param message
     */
    public static void fatal(String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.fatal(message);
    }

    /**
     * @param message
     */
    public static void trace(String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.trace(message);
    }
    /**
     * @param message
     */
    public static void trace(String flag , String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.info("[" + flag + "] " +message);
    }
    /**
     * @param message
     */
    public static void trace(String flag1,String flag2,String message) {
        Log log = LogFactory.getLog(Reflection.getCallerClass(2));
        log.info("[" + flag1 + "] " + "[" + flag2 + "] " +message);
    }

    /**
     * 字符串伪变量替换
     * 
     * @param input
     * @param reservedWords
     * @return
     */
    public static String replace(String input, Map reservedWords) {
        if (reservedWords == null || reservedWords.isEmpty() || COMMON.isEmpty(input))
            return input;
        StringBuffer result = new StringBuffer(200);
        StringBuffer buff = new StringBuffer(20);
        for (int index = 0; index < input.length(); index++) {
            char c = input.charAt(index);
            if (c == '{') {
                result.append(buff.substring(0, buff.length()));
                buff.delete(0, buff.length());
                buff.append(c);
            } else if (c == '}') {
                buff.append(c);
                String key = buff.substring(0, buff.length());
                String value = (String) reservedWords.get(key);
                if (value != null) {
                    result.append(value);
                } else {
                    result.append(key);
                }
                buff.delete(0, buff.length());
            } else {
                buff.append(c);
            }
        }
        result.append(buff);
        return result.toString();
    }

    /**
     * 获取字符串的伪变量
     * 
     * @param input
     * @return
     * 
     */
    public static Map getParam(String input) {
        StringBuffer buff = new StringBuffer(20);
        Map paramMap = new HashMap();
        for (int index = 0; index < input.length(); index++) {
            char c = input.charAt(index);
            if (c == '{') {
                buff.delete(0, buff.length());
                buff.append(c);
            } else if (c == '}') {
                buff.append(c);
                String key = buff.substring(0, buff.length());
                paramMap.put(key, key);
            } else {
                buff.append(c);
            }
        }
        return paramMap;
    }
    public static String getRandomString(int size) {
        char[] c = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o',
                'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm' };
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < size; ++i)
            sb.append(c[(Math.abs(random.nextInt()) % c.length)]);

        return sb.toString();
    }
	
    public static String getRandomString1(int size) {
        char[] c = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < size; ++i)
            sb.append(c[(Math.abs(random.nextInt()) % c.length)]);

        return sb.toString();
    }
    
    /**
     * 把String转成unicode用于比如WebSphere 传JSON的乱码问题，
     * 一般配合前台pccw.js的unicodeToString
     * 或者后台COMMON的unicodeToString方法
     * 
     * @param String 要转的String.
     * @return String 转过的unicode.
     * 
     */
    public static String stringToUnicode(String str) {  
        str = (str == null ? "" : str);  
        String tmp;  
        StringBuffer sb = new StringBuffer();  
        char c;  
        int i, j;  
        sb.setLength(0);  
        for (i = 0; i < str.length(); i++) {  
            c = str.charAt(i);  
            sb.append("\\u");  
            j = (c >>> 8);  
            tmp = Integer.toHexString(j);  
            if (tmp.length() == 1)  
                sb.append("0");  
            sb.append(tmp);  
            j = (c & 0xFF);  
            tmp = Integer.toHexString(j);  
            if (tmp.length() == 1)  
                sb.append("0");  
            sb.append(tmp);  
  
        }  
        return (new String(sb));  
    }
    
    /**
     * 把unicode转成String用于比如WebSphere传JSON的乱码问题，
     * 一般配合前台pccw.js的stringToUnicode
     * 或者后台COMMON的stringToUnicode方法
     * 
     * @param String 要转的unicode.
     * @return String 转过的String.
     * 
     */
    public static String unicodeToString(String str) {  
        str = (str == null ? "" : str);  
        if (str.indexOf("\\u") == -1)
            return str;  
        StringBuffer sb = new StringBuffer(); 
        for (int i = 0; i <= str.length() - 6;) {
            String strTemp = str.substring(i, i + 6);  
            String value = strTemp.substring(2);  
            int c = 0;  
            for (int j = 0; j < value.length(); j++) {  
                char tempChar = value.charAt(j);  
                int t = 0;  
                switch (tempChar) {  
                case 'a':  
                    t = 10;  
                    break;  
                case 'b':  
                    t = 11;  
                    break;  
                case 'c':  
                    t = 12;  
                    break;  
                case 'd':  
                    t = 13;  
                    break;  
                case 'e':  
                    t = 14;  
                    break;  
                case 'f':  
                    t = 15;  
                    break;  
                default:  
                    t = tempChar - 48;  
                    break;  
                }  
  
                c += t * ((int) Math.pow(16, (value.length() - j - 1)));  
            }  
            sb.append((char) c);  
            i = i + 6;  
        }  
        return sb.toString();  
    }
    
    
    
    

	/**
	 * 数字千分位格式化12345->12,345
	 * @param number
	 * @return
	 * @throws Exception 
	 */
	public static String fmtNum(String number) throws Exception{
		String result = number;
      if(number!=null&&!"".equals(number)&&!"null".equals(number)){
		DecimalFormat df = new DecimalFormat();
		df.applyPattern("0,000");
		if (number.length() > 3) {
			result = df.format(Double.parseDouble(number));
		}
		}else{
			result="";
		}
		return result;
	}
	
	/**
	 * 数字千分位反格式化12,345->12345
	 * @param number
	 * @return
	 */
	public static String parseNum(String number) {
	    if(number!=null&&!"".equals(number)&&!"null".equals(number)){
		if(number.indexOf(",")!=-1){
			StringUtil.replace(number, ",", "");
		}
	    }else{
	    	number="";
	    }
		return number;
	}
	/**
	 * 小数转成百分比
	 * */
	public static String decimalPercentage(Object number){
		
		String num="";
		if(number!=null&&!"".equals(number)&&!"null".equals(number)){
			NumberFormat nt = NumberFormat.getPercentInstance();
			nt.setMaximumFractionDigits(2);
			num=nt.format(number);
			
		}else{
			number="";
		}
		return num;
	}
	
	/**
	 * 按照参数保留小数点
	 * @param num操作数 pointCount保留小数点位数  
	 * @throws Exception
	 */
	public static String pointNum(String number , String decimalPlace){
		int pointCount=Integer.parseInt(decimalPlace);
		if(number!=null&&!"".equals(number)&&!"null".equals(number)){
	        	if(number.indexOf(".")!=-1){
		    	int relCount = number.substring(number.indexOf(".")).length()-1;
			if(relCount<=pointCount){
				for(int i = 0 ; i < pointCount-relCount;i++){
					number = number.concat("0");
				}
			}else{
				number = number.substring(0,number.length()-relCount+pointCount);
				if(pointCount==0){
					number = StringUtil.replace(number, ".", "");
				}
			}
		}else{
			number = number.concat(".");
			for(int i =0 ; i < pointCount ; i++){
				number = number.concat("0");
			}
		}
		}else{
			number="";
		}
		return number;
	}
	
	/**
	 * 金额转换为大写
	 * @param value 需要转换的金额
	 * @return
	 */
	public static String changeToBig(String number) {
		double value=0;
	    if(number!=null&&!"".equals(number)&&!"null".equals(number)){
		 value=Double.parseDouble(number);
		}else{
			return "";
		}
		if((""+value).length()>12){
			return "数额过大";
		}
		char[] hunit = { '拾', '佰', '仟' };
		char[] vunit = { '万', '亿' };  
		char[] digit = { '零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖' }; 
		long midVal = (long) (value * 100);//转化成整形   
		String valStr = String.valueOf(midVal);//转化成字符串   
		String head = valStr.substring(0, valStr.length() - 2);//取整数部分   
		String rail = valStr.substring(valStr.length() - 2);//取小数部分   
		String prefix = "";//整数部分   
		String suffix = "";//小数部分   
		//处理小数点后面的数   
		if (rail.equals("00")) {
			//如果小数部分为0   
			suffix = "整";
		} else {
			//否则把角分转化出来 
			suffix = digit[rail.charAt(0) - '0'] + "角"+ digit[rail.charAt(1) - '0'] + "分";
		}
		//处理整数部分  
		char[] chDig = head.toCharArray();//把整数部分转化成字符数组   
		char zero = '0';//标志'0'表示出现过0   
		byte zeroSerNum = 0;//连续出现0的次数   
		for (int i = 0; i < chDig.length; i++) {
			//循环处理每个数字   
			int idx = (chDig.length - i - 1) % 4;
			//取段内位置   
			int vidx = (chDig.length - i - 1) / 4;
			//取段位置   
			if (chDig[i] == '0') {
				//如果当前字符是0   
				zeroSerNum++;
				//连续0次数递增   
				if (zero == '0') {
					//标志   
					zero = digit[0];
				} else if (idx == 0 && vidx > 0 && zeroSerNum < 4) {
					prefix += vunit[vidx - 1];
					zero = '0';
				}
				continue;
			}
			zeroSerNum = 0;
			//连续0次数清零   
			if (zero != '0') {
				//如果标志不为0,则加上,例如万,亿什么的   
				prefix += zero;
				zero = '0';
			}
			prefix += digit[chDig[i] - '0'];
			//转化该数字表示   
			if (idx > 0)
				prefix += hunit[idx - 1];
			if (idx == 0 && vidx > 0) {
				prefix += vunit[vidx - 1];
				//段结束位置应该加上段名如万,亿   
			}
		}
		if (prefix.length() > 0)
			prefix += '圆';
		//如果整数部分存在,则有圆的字样   
		return prefix + suffix;
		//返回正确表示   
	}
	
	public static String getIpAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if ((ip == null) || (ip.length() == 0)
				|| ("unknown".equalsIgnoreCase(ip))) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}



	public static int NulltoZero(Integer integer) {
		// TODO Auto-generated method stub
		if(isEmpty(integer))
		return 0;
		else return integer;
	}

	public static Object Nulltonull(Object obj) {
		// TODO Auto-generated method stub
		if(obj == null)
		return "null";
		else return obj;
	}

	public static Double ZerotoLongi(Double double1) {

		if(double1 == null)
		return 116.467618;
		else return double1;
	}


	public static Double ZerotoLati(Double double1) {
		if(double1 == null)
		return 39.994581;
		else return double1;
	}

	public static String NulltoAvatar(String str) {
		// TODO Auto-generated method stub
		if(str == null)
			return "resource/default_avatar.jpg";
		return str;
	}

	public static String NulltoBlank(String str) {
		// TODO Auto-generated method stub
		if(str == null)
			return "";
		return str;
	}

	public static Object NulltoBlank(Object ob) {
		// TODO Auto-generated method stub
		if(ob == null)
			return "";
		return ob;
	}
	
	public static String NulltoThree(String integer) {
		// TODO Auto-generated method stub
		if(integer == null)
		return "3";
		else return integer;
	}

	public static int NulltoThree(Integer integer) {
		// TODO Auto-generated method stub
		if(integer == null)
		return 3;
		else return integer;
	}


	public static String Nullto400phone(String string) {
		// TODO Auto-generated method stub
		if(string == null)
		return "4006968787";
		else return string;
	}


	public static int NulltoFive(Integer integer) {
		// TODO Auto-generated method stub
		if(integer == null)
		return 5;
		else return integer;
	}

	public static Double NulltoFive(Double db) {
		// TODO Auto-generated method stub
		if(db == null)
		return 5.0;
		else return db;
	}

	public static boolean isnull(Object obj) {
		// TODO Auto-generated method stub
		if(obj == null) return true;
		return false;
	}
	
	public static double Decimal2dot(Double obj) {
		// TODO Auto-generated method stub
		if(obj == null)return 0.00;
        BigDecimal bd  =   new   BigDecimal(obj);  
        double   f1   =   bd.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();  
		return f1;
	}
	public static double Decimal1dot(Double obj) {
		// TODO Auto-generated method stub
		if(obj == null)return 0.0;
        BigDecimal bd  =   new   BigDecimal(obj);  
        double   f1   =   bd.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue();  
		return f1;
	}

	//根据单课或是班课,生成price的字符串.单课则读取type为1和2和3的最小最大值,班课则读取type为4的值.
	public static String FormatPriceStr(
			List<Map<String, Object>> teach_typeprice_json,int mode) {
		// TODO Auto-generated method stub
		String price_str;
		double []price = new double[3];
		double price4=0;
		boolean has4 = false;
		int j = 0;
		for(Map<String,Object> map : teach_typeprice_json)
		{
			if(Integer.parseInt(map.get("type").toString()) == 4)
			{
				price4 = Double.parseDouble(map.get("typeprice").toString());
				has4 = true;
			}
			else
				price[j++] = Double.parseDouble(map.get("typeprice").toString());
		}
		if(mode != 1){if(has4)price_str = price4 + "元/课时"; else price_str = "教师未设定 元/课时";}
		else {
			if(j == 0 )price_str = "教师未设定 元/课时";
			double max = -1,min = 9999999;
			for(int ii = 0 ;ii < j; ii++)
			{
				max = Math.max(max,price[ii]);
				min = Math.min(min,price[ii]);
			}
			if(max == min)price_str = max + "元/课时";
			else price_str = min + "--" + max + "元/课时";
		}
		return price_str;
		
	}


}
